﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace RouterControl.WhsAddIn.ConsoleControls
{
    public partial class ConnectingRouter : ConsoleControlBase
    {
        public ConnectingRouter(RouterControlConsoleTab2 tab)
			: base(tab)
		{
			if (_log.IsDebugEnabled)
				_log.Debug("Initialization start");

			try
			{
				InitializeComponent();
	
				this.lineBox.Header.Text = Properties.Resources.txtSelectedRouter;

				// done
				if (_log.IsDebugEnabled)
					_log.Debug("Initialization done");
			}
			catch (Exception e)
			{
				_log.Fatal("Failed to initialize", e);

				throw;
			}
		}

        private void connectingBgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                _singletonService.Channel.EnsureFirstSearchForDevices(true);

            }
            catch (Exception x)
            {
                _log.Error("Failed to wait for device search", x);
            }
        }

        private void connectingBgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                var found = _singletonService.Channel.IsSelectedDeviceFound();

                _tab.SetState(
                    found ?
                    RouterControlConsoleTab2.RouterState.RouterPresent :
                    RouterControlConsoleTab2.RouterState.RouterMissing
                    );

            }
            catch (Exception x)
            {
                _log.Error("Failed to handle slected-device-found status", x);

                throw;
            }
        }

        private void ConnectingRouter_Load(object sender, EventArgs e)
        {
            this.connectingBgWorker.RunWorkerAsync();
        }
    }
}
